package com.hk.modules.node.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hk.common.constant.Constants;
import com.hk.common.query.QueryGenerator;
import com.hk.common.utils.ResponseUtils;
import com.hk.modules.node.pojo.NodePojo;
import com.hk.modules.node.service.NodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zy
 * @since 2024-04-17
 */
@Controller
@RequestMapping("/node")
public class NodeController {

    @Autowired
    private NodeService nodeService;


    @PostMapping("/add")
    public ResponseEntity<Object> addObj(@RequestBody NodePojo p){
        p.setCreateTime(new Date()).setUpdateTime(new Date());
        if(p.getOrderNum()==null){
            QueryWrapper<NodePojo> queryWrap = new QueryWrapper<>();
            queryWrap.eq("circuit_id",p.getCircuitId());
            queryWrap.orderByDesc("order_num");
            List<NodePojo> list = nodeService.list(queryWrap);
            if(list.size()>0){
                p.setOrderNum(list.get(0).getOrderNum()+1);
            }else{
                p.setOrderNum(Constants.ONE);
            }
        }
        return ResponseUtils.tryReturn("新增信息异常",()-> nodeService.save(p));
    }

    @PostMapping("/update")
    public ResponseEntity<Object> updateObj(@RequestBody NodePojo p){
        p.setUpdateTime(new Date());
        return ResponseUtils.tryReturn("修改信息异常",()->
                nodeService.updateById(p));
    }

    @PostMapping("/delete")
    public ResponseEntity<Object> deleteObj(@RequestBody NodePojo p){
        return ResponseUtils.tryReturn("删除信息异常",()->
                nodeService.removeById(p.getId()));
    }


    @GetMapping("/listPage")
    public ResponseEntity<Object> listPage(@RequestParam(name="current", defaultValue="1") Integer current,
                                           @RequestParam(name="size", defaultValue="10") Integer size,
                                           NodePojo Node, HttpServletRequest request){
        QueryWrapper<NodePojo> queryWrapper = QueryGenerator.initQueryWrapper(Node, request.getParameterMap());
        Page<NodePojo> page = new Page<>(current, size);
        return ResponseUtils.tryReturn("查询信息异常",()->nodeService.page(page, queryWrapper));
    }


    @GetMapping("/list")
    public ResponseEntity<Object> listNode(NodePojo Node, HttpServletRequest request){
        QueryWrapper<NodePojo> queryWrapper = QueryGenerator.initQueryWrapper(Node, request.getParameterMap());
        return ResponseUtils.tryReturn("查询信息异常",()->nodeService.list(queryWrapper));
    }


}

